﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;

namespace PodcastGenerator
{
    public class CsvStore : Store
    {
        private readonly string _csvStorePath;
        public const string  CsvStoreName = "SermonCsvStore";

        public CsvStore(ISermonDownloader sermonDownloader, string csvStorePath)
        {
            if (!Directory.Exists(csvStorePath))
            {
                Directory.CreateDirectory(csvStorePath);
            }

            _csvStorePath = csvStorePath;
            SermonDownloader = sermonDownloader;
        }

        public string CsvFileName
        {
            get { return string.Format("{0}\\{1}.csv", _csvStorePath, CsvStoreName); }
        }

        protected override void PersistToDataStore(IEnumerable<ISermon> sermons, bool append)
        {
            if (!append)
                WriteHeader(CsvFileName);

            foreach (var line in sermons.Select(sermon => string.Format("{0},{1},{2},{3},{4},{5}{6}", sermon.Date, sermon.Title, sermon.Pastor, sermon.Ref, sermon.DownloadUri, sermon.FileSize, Environment.NewLine)))
            {
                File.AppendAllText(CsvFileName, line);
            }
        }

        private static void WriteHeader(string csvFilename)
        {
            var headerText = string.Format("DateTime,Title,Pastor,Ref,DownloadUri,FileSize{0}", Environment.NewLine);
            File.WriteAllText(csvFilename, headerText);
        }
    }
}